package com.bbkb.quartz.resolver;

import cn.hutool.json.JSONUtil;
import com.bbkb.common.exception.BaseException;
import com.bbkb.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;


/**
 * 异常解析器
 */
@ControllerAdvice
@Slf4j
public class ExceptionResolver {

    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public Result baseExceptionHandler(HttpServletRequest request, BaseException e) {
        log.error(MessageFormat.format("请求{0}出现错误", this.getReqMap(request)),e);
        return new Result(e.getDetail());
    }

    /**
     * 异常分类处理
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest request, Exception e) {
        log.error(MessageFormat.format("请求{0}出现错误", this.getReqMap(request)), e);
        return new Result("请求出现异常，请刷新页面重试");
    }

    private String getReqMap(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        params.put("url", request.getRequestURL().toString());
        params.put("params", request.getParameterMap());
        return JSONUtil.toJsonStr(params);
    }

}
